package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.context.BaseContext;
import org.example.mapper.PostMapper;
import org.example.pojo.*;
import org.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Override
    public PageResult<PostVO> getPosts(Integer page, Integer pageSize, String type) {
        PageHelper.startPage(page, pageSize);
        Long userId = BaseContext.getCurrentId();
        Page<PostVO> posts = postMapper.selectPosts(type, userId);
        log.info("获取到的posts：{}", posts);
        return new PageResult<>(posts.getTotal(), posts.getResult());
    }

    @Override
    @Transactional
    public Map<String, Object> toggleLike(Long userId, Long postId) {
        // 检查是否已点赞
        boolean isLiked = postMapper.checkLike(userId, postId) > 0;
        
        if (isLiked) {
            postMapper.deleteLike(userId, postId);
            postMapper.decrementLikes(postId);
        } else {
            postMapper.insertLike(userId, postId);
            postMapper.incrementLikes(postId);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("likes", postMapper.getLikes(postId));
        result.put("isLiked", !isLiked);
        return result;
    }

    @Override
    public CommentVO addComment(Long userId, Long postId, String content) {
        Comment comment = new Comment();
        comment.setPostId(postId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setCreateTime(LocalDateTime.now());
        
        postMapper.insertComment(comment);
        
        User user = postMapper.getUser(userId);
        
        CommentVO vo = new CommentVO();
        vo.setId(comment.getId());
        vo.setUsername(user.getUsername());
        vo.setContent(content);
        vo.setTime(comment.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return vo;
    }
} 